package com.xoa.service.cms.core;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.GetMethod;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
* @author 程叶同
* @date 2018/8/13 14:50
* @desc  cms解析数据工具包
*/
public class FileUtils {

    /**
     * 复制文件夹从${form}到${to}
     *
     * @param from
     * @param to
     * @return
     */
    public static boolean copyDirs(String from, String to) {
        File fromFile = new File(from);
        if (!fromFile.exists() || !fromFile.isDirectory()) {
            return false;
        }
        File toFileDirectory = new File(to);

        if (!toFileDirectory.exists()) {
            toFileDirectory.mkdirs();
        }

        copyDirs0(from, to);

        return true;
    }

    /**
     * 把文件中的内容读入数组，每行作为一个元素
     *
     * @param
     * @return
     * @throws Exception
     */
    public static void storeString2File(String fileName, String content)
            throws Exception {
        OutputStream outs = null;
        try {
            File file = new File(fileName);
            File outDir = file.getParentFile();
            if (!outDir.exists()) {
                outDir.mkdirs();
            }
            if (!file.exists()) {
                file.createNewFile();
            }
            if (!file.canWrite()) {
                file.setWritable(true);
            }
            outs = new FileOutputStream(file);
            storeString2File(outs, content, "UTF-8");
        } catch (Exception ex) {
            throw ex;
        } finally {
            try {
                if (outs != null) {
                    outs.close();
                }
            } catch (Exception ex) {
            }
        }
    }
    /**
     * 把数组中的内如输出到流中，每个元素作为一行
     *
     * @param out
     * @param
     * @throws Exception
     */
    public static void storeString2File(OutputStream out, String str,
                                        String charSet) throws Exception {
        if (str == null) {
            return;
        }
        OutputStreamWriter writer = null;
        try {
            if (charSet != null) {
                writer = new OutputStreamWriter(out, charSet);
            } else {
                writer = new OutputStreamWriter(out);
            }
            writer.write(str);
            writer.flush();
        } catch (Exception ex) {
            throw ex;
        } finally {
            try {
                if (writer != null) {
                    writer.close();
                }
            } catch (Exception ex) {
            }
        }
    }

    /**
     * 把文件加载到字节数组
     *
     * @param fileName
     */
    public static byte[] loadFile2Bytes(String fileName) throws Exception {
        InputStream in = null;
        try {
            File file = new File(fileName);
            if (!file.exists()) {
                return null;
            }
            in = new FileInputStream(fileName);
            int fileLength = (int) file.length();
            byte[] buff = new byte[fileLength];
            in.read(buff, 0, fileLength);

            return buff;
        } catch (Exception ex) {
            throw ex;
        } finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception ex) {
            }
        }
    }

    private static void copyDirs0(String from, String to) {
        File fromFile = new File(from);
        File toFile = new File(to);
        toFile.mkdirs();
        File list[] = fromFile.listFiles();
        for (File f : list) {
            if (f.isDirectory()) {
                copyDirs0(f.getAbsolutePath(), to + "/" + f.getName());
            } else {
                copy(f.getAbsolutePath(), to);
            }
        }
    }


    /**
     * 复制文件从${form}到${to}
     *
     * @param from
     * @param to
     * @return
     */
    public static boolean copy(String from, String to) {
        File fromFile = new File(from);
        if (!fromFile.exists() || !fromFile.isFile()) {
            return false;
        }
        File toFileDirectory = new File(to);

        if (!toFileDirectory.exists()) {
            toFileDirectory.mkdirs();
        }

        FileInputStream input = null;
        FileOutputStream output = null;
        byte b[] = new byte[1024];
        int i = 0;
        try {
            input = new FileInputStream(fromFile);
            output = new FileOutputStream(new File(to + "/"
                    + fromFile.getName()));
            while ((i = input.read(b)) != -1) {
                output.write(b, 0, i);
            }
            return true;
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return false;
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return false;
        } finally {
            try {
                input.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            try {
                output.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }

    public static String getString(Object str){
        if(str==null){
            return "";
        }
        return String.valueOf(str);
    }

    public static String getString(Object obj, String str1){
        if(obj==null || "".equals((String)obj.toString())){
            return str1;
        }
        return (String)obj.toString();
    }



    /**
     * 将Date类型转换为字符串
     *
     * @param date
     *            日期类型
     * @return 日期字符串
     */
    public static String format(Date date) {
        if(date == null){
            return "";
        }
        return format(date, "yyyy-MM-dd HH:mm:ss");
    }

    public static String format(Calendar date) {
        if(date == null){
            return "";
        }
        return format(date.getTime(), "yyyy-MM-dd HH:mm:ss");
    }

    /**
     * 将Date类型转换为字符串
     *
     * @param date
     *            日期类型
     * @param pattern
     *            字符串格式
     * @return 日期字符串
     */
    public static String format(Date date, String pattern) {
        if (date == null) {
            return "null";
        }
        if (pattern == null || pattern.equals("") || pattern.equals("null")) {
            pattern = "yyyy-MM-dd HH:mm:ss";
        }
        return new java.text.SimpleDateFormat(pattern).format(date);
    }


    public static String replaceImageUrl(List oldUrls , String content, List newUrls)
    {
        String result=null;
        /**最好不要对参数修改*/
        result=content;
        for(int i=0;i<oldUrls.size();i++){
            String url=(String)oldUrls.get(i);
            if(url!=null)
            {
                result=result.replace(url,(String)newUrls.get(i));

            }
        }
        return result;
    }


    public static Date parseCalendar(String dateStr){
        Date c= null;
        try {
           // c.setTime(parseDateByPattern(dateStr));
            c=parseDateByPattern(dateStr);
        } catch (Exception e) {
            // TODO Auto-generated catch block
//				e.printStackTrace();
            return null;
        }
        return c;
    }
    /**
     * 格局传入的日期 解析出 该用何种SimpleDateFormat
     * @param dateStr
     * @return
     * @throws
     */
    public static Date parseDateByPattern(String dateStr){
        SimpleDateFormat format = null;
        try{
            if (Pattern.matches("\\d{4}-\\d{2}-\\d{2}", dateStr)) {
                format = new SimpleDateFormat("yyyy-MM-dd");
                return format.parse(dateStr);
            }else if (Pattern.matches("\\d{4}-\\d{1,2}-\\d{1,2}", dateStr)) {
                format = new SimpleDateFormat("yyyy-MM-dd");
                return format.parse(dateStr);
            }else if (Pattern.matches("\\d{4}/\\d{2}/\\d{2}", dateStr)) {
                format = new SimpleDateFormat("yyyy/MM/dd");
                return format.parse(dateStr);
            }else if (Pattern.matches("\\d{4}/\\d{1,2}/\\d{1,2}", dateStr)) {
                format = new SimpleDateFormat("yyyy/MM/dd");
                return format.parse(dateStr);
            }else if (Pattern.matches("\\d{4}\\d{2}\\d{2}", dateStr)) {
                format = new SimpleDateFormat("yyyyMMdd");
                return format.parse(dateStr);
            }else if (Pattern.matches("\\d{4}年\\d{2}月\\d{2}日", dateStr)) {
                format = new SimpleDateFormat("yyyy年MM月dd日", Locale.CHINA);
                return format.parse(dateStr);
            }else if (Pattern.matches("\\d{4}年\\d{1,2}月\\d{1,2}日", dateStr)) {
                format = new SimpleDateFormat("yyyy年MM月dd日", Locale.CHINA);
                return format.parse(dateStr);
            }else if (Pattern.matches("\\d{4}/\\d{1,2}/\\d{1,2} \\d{2}:\\d{2}", dateStr)) {
                format = new SimpleDateFormat("yyyy/MM/dd HH:mm", Locale.CHINA);
                return format.parse(dateStr);
            }else if (Pattern.matches("\\d{4}\\.\\d{2}\\.\\d{2}", dateStr)) {
                format = new SimpleDateFormat("yyyy.MM.dd", Locale.CHINA);
                return format.parse(dateStr);
            }else if (Pattern.matches("\\d{4}\\.\\d{1,2}\\.\\d{1,2}", dateStr)) {
                format = new SimpleDateFormat("yyyy.MM.dd", Locale.CHINA);
                return format.parse(dateStr);
            }else if (Pattern.matches("\\d{4}年\\d{2}月", dateStr)) {
                format = new SimpleDateFormat("yyyy年MM月", Locale.CHINA);
                return format.parse(dateStr);
            }else if (Pattern.matches("\\d{4}年\\d{1,2}月", dateStr)) {
                format = new SimpleDateFormat("yyyy年MM月", Locale.CHINA);
                return format.parse(dateStr);
            }else if (Pattern.matches("\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}:\\d{2}", dateStr)) {
                format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.CHINA);
                return format.parse(dateStr);
            }else if (Pattern.matches("\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}", dateStr)) {
                format = new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.CHINA);
                return format.parse(dateStr);
            }else if (Pattern.matches("\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}:\\d{2}\\.\\d{3}", dateStr)) {
                format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS", Locale.CHINA);
                return format.parse(dateStr);
            }else if (Pattern.matches("\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}:\\d{2}\\.\\d{2}", dateStr)) {
                format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SS", Locale.CHINA);
                return format.parse(dateStr);
            }else if (Pattern.matches("\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}:\\d{2}\\.\\d{1}", dateStr)) {
                format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S", Locale.CHINA);
                return format.parse(dateStr);
            }else if (Pattern.matches("\\d{2}:\\d{2}", dateStr)) {
                format = new SimpleDateFormat("HH:mm", Locale.CHINA);
                return format.parse(dateStr);
            }
        }catch(Exception e){

        }
        return null;
    }

    /**
     * 从HTML源码中提取图片路径，最后以一个 String 类型的 List 返回，如果不包含任何图片，则返回一个 size=0　的List
     * 需要注意的是，此方法只会提取以下格式的图片：.jpg|.bmp|.eps|.gif|.mif|.miff|.png|.tif|.tiff|.svg|.wmf|.jpe|.jpeg|.dib|.ico|.tga|.cut|.pic
     * @param htmlCode HTML源码
     * @return <img>标签 src 属性指向的图片地址的List集合
     * @author Carl He
     */
    public static List<String> getImageSrc(String htmlCode) {
        List<String> imageSrcList = new ArrayList<String>();
        Pattern p= Pattern.compile("<img[^>]*\\bsrc\\b\\s*=\\s*('|\")?([^'\"\n\r\f>]+(\\.jpg|\\.bmp|\\.eps|\\.gif|\\.mif|\\.miff|\\.png|\\.tif|\\.tiff|\\svg|\\.wmf|\\.jpe|\\.jpeg|\\.dib|\\.ico|\\.tga|\\.cut|\\.pic)\\b)[^>]*>", Pattern.CASE_INSENSITIVE);
        Pattern p2 = Pattern.compile("<img[^>]*src\\s*=\\s*('|\")?([^'\"\n\r\f>]+(\\.jpg|\\.bmp|\\.eps|\\.gif|\\.mif|\\.miff|\\.png|\\.tif|\\.tiff|\\svg|\\.wmf|\\.jpe|\\.jpeg|\\.dib|\\.ico|\\.tga|\\.cut|\\.pic))[^>]*>", Pattern.CASE_INSENSITIVE);

        Matcher m = p.matcher(htmlCode);
        String quote = null;
        String src = null;
        while (m.find()) {
            quote = m.group(1);  //判断是否有双引号和单引号
            src = (quote == null || quote.trim().length() == 0) ? m.group(2).split("\\s+")[0] : m.group(2);
            imageSrcList.add(src);
        }
        return imageSrcList;
    }

    /**
     * 下载远程图片
     * @param url
     * @param
     */
    public static InputStream download(String url)
    {
        HttpClient client = new HttpClient();
        GetMethod get = new GetMethod(url);
        try {
            client.executeMethod(get);
            InputStream inputStream = get.getResponseBodyAsStream();
            return inputStream;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }
    /**
     * @author 程叶同
     * @date 2018/8/13 14:27
     * @desc  数字判空处理
     */
    public static int getInteger(Object str,int def){
        String s = "";
        if (str != null) {
            s=String.valueOf(str);
        }
        int dot = s.indexOf('.');
        if(dot!=-1){
            s = s.substring(0, dot);
        }
        if(!"".equals(s)){
            try{
                return Integer.parseInt(s);
            }catch(Exception e){
                return def;
            }
        }
        return def;
    }


}
